
const formatDate = function (date, fmt = 'yyyy-MM-dd') {
    // debugger
    if (!date) return '';
    date = new Date(date);
    if (/(y+)/.test(fmt)) {
        fmt = fmt.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length))
    }
    let o = {
        'M+': date.getMonth() + 1,
        'd+': date.getDate(),
        'h+': date.getHours(),
        'm+': date.getMinutes(),
        's+': date.getSeconds(),
        'i+': date.getMilliseconds(),
    }
    for (let k in o) {
        if (new RegExp(`(${k})`).test(fmt)) {
            let str = o[k] + ''
            fmt = fmt.replace(RegExp.$1, RegExp.$1.length === 1 ? str : padLeftZero(str))
        }
    }
    return fmt
    function padLeftZero(str) {
        let tmpStr = '00'
        if (str.length === 3) {
            tmpStr = '000'
        }
        return (tmpStr + str).substr(str.length)
    }
}

const formatDateTime = date => {
    return formatDate(new Date(date), 'yyyy-MM-dd hh:mm:ss')
}
const formatDateMinute = date => {
    return formatDate(new Date(date), 'yyyy-MM-dd hh:mm')
}
const formatTime = date => {
    return formatDate(new Date(date), 'mm:ss')
}
const formatMoney = (n) => {
    if (!/^(0|[1-9]\d*)(\.\d+)?$/.test(n))
        return "数据非法";
    var unit = "千百拾亿千百拾万千百拾元角分", str = "";
    n += "00";
    var p = n.indexOf('.');
    if (p >= 0)
        n = n.substring(0, p) + n.substr(p + 1, 2);
    unit = unit.substr(unit.length - n.length);
    for (var i = 0; i < n.length; i++)
        str += '零壹贰叁肆伍陆柒捌玖'.charAt(n.charAt(i)) + unit.charAt(i);
    return str.replace(/零(千|百|拾|角)/g, "零").replace(/(零)+/g, "零").replace(/零(万|亿|元)/g, "$1").replace(/(亿)万|壹(拾)/g, "$1$2").replace(/^元零?|零分/g, "").replace(/元$/g, "元整");
}
const omit = (str, count = 20) => {
    if (str == null) return null;
    if (str.length <= count) {
        return str;
    }
    if (str.length > count) {
        return str.substring(0, count) + '..'
    }
}
const formatHidePart = (str, a = 4, b = 4) => {
    var c = str.length - a - b;
    var rega = new RegExp("(\\w{" + a + "})\\w{" + c + "}(\\w{" + b + "})", "ig");
    return str.replace(rega, '$1****$2');
}

const formatWeek = (dateOrNo, fmt = "周") => {
    let index = /^\d$/.test(dateOrNo) ? dateOrNo : new Date(dateOrNo).getDay();
    let arrWeek = new Array("日", "一", "二", "三", "四", "五", "六");
    return fmt + arrWeek[index];
};

const capitalize = str => {
    if (!str) return ''
    str = str.toString()
    return str.charAt(0).toUpperCase() + str.slice(1)
};

const dateAdd = (date, n) => {
    date = new Date(date)
    return new Date(date.setDate(date.getDate() + n))
};
const deepCopy = (obj) => {
    return JSON.parse(JSON.stringify(obj))
};

const random = (min, max) => {
    return parseInt(Math.random() * (max - min + 1) + min, 10);
};
const partStr = (value, count = 10) => {
    if (value == null) return null;
    if (value.length <= count) {
        return value;
    }
    if (value.length > count) {
        return value.substring(0, count) + '...'
    }
};
const getAgeCeil = (birthday) => {
    //出生时间 毫秒
    var birthDayTime = new Date(birthday).getTime();
    //当前时间 毫秒
    var nowTime = new Date().getTime();
    //一年毫秒数(365 * 86400000 = 31536000000)
    return Math.ceil((nowTime - birthDayTime) / 31536000000);
}
const getAgeDay = (birthday, type = 0) => {
    if (!birthday) return '';
    if (new Date(birthday) > new Date()) return '';
    var date = new Date(birthday);
    var now = new Date();
    var bigYear = now.getFullYear();
    var bigMonth = now.getMonth();
    var bigDay = now.getDate();

    var smallYear = date.getFullYear();
    var smallMonth = date.getMonth();
    var smallDay = date.getDate();
    var year = bigYear - smallYear;
    var month = bigMonth - smallMonth;
    var day = bigDay - smallDay;
    if (day < 0) {
        var perDay = new Date(date.getFullYear(), date.getMonth() + 1, 0).getDate() - date.getDate()
        var afterDay = now.getDate()
        day = perDay + afterDay
        bigMonth--
        if (bigMonth < 0) {
            bigMonth = bigMonth + 12
            year--
        }
    }
    if (month < 0) {
        month = 12 - (date.getMonth() + 1) + (now.getMonth() + 1)
        year--
    }
    //var month = bigMonth - smallMonth;
    year = year || ''
    month = month || ''
    day = day || ''
    var resStr = "";
    if (type === 0) {
        resStr = `${(year && (year + '岁')) + (month && (month + '个月')) + (day && (day + '天'))}`
    }
    return resStr;
}
const comInfo = (arr) => {
    if (!Array.isArray(arr)) return null;
    if (arr.length == 1) return arr[0];
    var res = ''
    var splitItem = arr.pop()
    if (arr.every(s => !s)) return splitItem
    for (let i = 0; i < arr.length; i++) {
        const e = arr[i];
        if (i != 0) {
            res += `${(e || '') && (splitItem + e)}`
        } else if (e) {
            res += e;
        }
    }
    return res;
}
const groupBy = (array, f) => {
    const groups = {};
    array.forEach(function (o) {
        const group = JSON.stringify(f(o));
        groups[group] = groups[group] || [];
        groups[group].push(o);
    });
    return Object.keys(groups).map(function (group) {
        return groups[group];
    });
}
const getUnixTime = (date) => {
    let _date=new Date(date)
   return Math.round(_date.getTime()/1000)
}
const listToTree=(list)=>{
    let result = list.reduce((prev, item) => {
      prev[item.parentId] ? prev[item.parentId].push(item) : (prev[item.parentId] = [item])
      return prev
    }, {})
    for (let prop in result) {
      result[prop].forEach((item, i) => {
        result[item.id] ? (item.children = result[item.id]) : ''
      })
    }
    return result[0]
  }
export default {
    // 函数名，【功能】（参数）[示例：xxxxx]  //不规范的将被删除
    formatDate: formatDate,         //【格式化日期】 (date, fmt='yyyy-MM-dd')
    formatMoney,        //【数值转大写金额】 (Num)1>壹
    partStr,        //【多余字符用...显示】(string,[显示字数,默认20])
    formatDateTime,     //【格式化时间为yyyy-MM-dd hh:mm:ss】'yyyy-MM-dd hh:mm:ss' 
    formatDateMinute,   //【格式化时间为yyyy-MM-dd hh:mm】 'yyyy-MM-dd hh:mm' 
    formatTime,     //【格式化时间为hh:mm】 ' hh:mm' 
    formatWeek,     //【格式化周】 (dateOrNo, fmt = "周") formatWeek(3) > "周三" ；formatWeek('2018-12-8','星期')> "星期六"
    formatHidePart,     //【隐藏部分字符串为*】(str, a=3, b=4)18205697425 > 188****8888【】
    omit,      //【隐藏多余字符为...】(str, cont=5) 更多新闻请点击 > 更多新闻请...
    capitalize,         //【首字母大写】(str) lzf > Lzf 
    dateAdd,            //【获取增加n天的时间】(date,n)  明天14点整：dateAdd(new Date().toLocaleDateString()+" 14:00:00",1) > Fri Jan 04 2019 14:00:00 GMT+0800 (中国标准时间) 
    random,         //【js随机数[min,max]】(min,max) random2(1,10)>1
    getAgeCeil,     //获取周岁
    getAgeDay,     //获取年龄[年月日]
    comInfo,//合并信息
    groupBy,//分组统计数量
    getUnixTime,//获取unix时间戳，基础单位：秒s
    listToTree,
    deepCopy,//深copy
}